﻿#include "widget.h"
#include "ui_widget.h"
#include <qthread.h>
#include <QUdpSocket>
#include <QDir>
#include <QFileDialog>
#include <QFile>
#include <QMetaType>
#include <future>
Widget::Widget(QWidget* parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    udpSocket = new QUdpSocket(this);
    connect(ui->pushButton, &QPushButton::clicked, this, &Widget::send);

    model = new QStringListModel(this);
    ui->listView->setModel(model);
    connect(ui->btnOpen, &QPushButton::clicked, this, &Widget::open);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::send()
{
    auto addHead = [](QByteArray& ba_, QByteArray fileName_, int& i) {
        int nameLen =fileName_.length();
        ba_.append(0xff & nameLen);
        ba_.append(0xff & (nameLen >> 8));
        ba_.append(0xff & (nameLen >> 16));
        ba_.append(0xff & (nameLen >> 24));

        ba_.append(fileName_);

        ba_.append(0xff & i);
        ba_.append(0xff & (i >> 8));
        ba_.append(0xff & (i >> 16));
        ba_.append(0xff & (i >> 24));
        ++i;
    };

    QStringList files = model->stringList();
    while (!files.isEmpty())
    {
        QFile file(files.takeFirst());
        file.open(QIODevice::ReadOnly);
        qDebug() << file.fileName();
        int i = 1;
        while (!file.atEnd())
        {
            QByteArray ba;
            QByteArray fileData(1024*7, 0);
            qint64 readLen = file.read(fileData.data(), fileData.size());
            addHead(ba, file.fileName().toUtf8(), i);
            ba.append(fileData.data(), readLen);
            qDebug() << " send :" << i << " " << udpSocket->writeDatagram(ba, QHostAddress::Broadcast, 16001);
        }
        // 文件传输结束
        i=0;
        QByteArray ba;
        addHead(ba, file.fileName().toUtf8(), i);
        udpSocket->writeDatagram(ba, QHostAddress::Broadcast, 16001);
    }
}

void Widget::open()
{
    auto dirPath = QFileDialog::getExistingDirectory(this, "E:/Image", "E:/Image", QFileDialog::DontResolveSymlinks);
    if (dirPath.isEmpty())return;
    QDir dir(dirPath);
    QStringList files;
    for (auto file : dir.entryList(QDir::Files))
        files.append(dir.absoluteFilePath(file));
    model->setStringList(files);
    ui->label_fileCount->setText(QString::asprintf("共 %d 个文件", files.count()));
}






